/**
 * @description 任务管理Vuex模块
 * @author AI Assistant
 * @date 2023-10-28
 */

import { Task } from '@/models/task';

// 存储key常量
const STORAGE_KEY = 'ticktock_tasks';

// 从本地存储加载任务数据
const loadTasksFromStorage = () => {
  try {
    const data = uni.getStorageSync(STORAGE_KEY);
    if (data) {
      // 将普通对象转换为Task实例
      const parsedTasks = JSON.parse(data).map(taskData => new Task(taskData));
      console.log('从本地存储加载任务数据:', parsedTasks.length);
      return parsedTasks;
    }
  } catch (error) {
    console.error('从本地存储加载任务数据失败:', error);
  }
  return null;
}

// 保存任务数据到本地存储
const saveTasksToStorage = (tasks) => {
  try {
    const data = JSON.stringify(tasks);
    uni.setStorageSync(STORAGE_KEY, data);
    console.log('保存任务数据到本地存储:', tasks.length);
  } catch (error) {
    console.error('保存任务数据到本地存储失败:', error);
  }
}

const state = {
  tasks: [],
  currentTaskId: ''
};

const getters = {
  getAllTasks: state => state.tasks,
  
  getCurrentTask: state => {
    return state.tasks.find(task => task.id === state.currentTaskId) || null;
  },
  
  // 获取指定分组的任务
  getTasksByGroup: state => groupId => {
    if (!groupId) return [];
    return state.tasks.filter(task => task.groupId === groupId);
  },
  
  // 获取指定分组的待办任务
  getTodoTasksByGroup: (state, getters) => groupId => {
    return getters.getTasksByGroup(groupId).filter(task => task.status === 'todo');
  },
  
  // 获取指定分组的进行中任务
  getDoingTasksByGroup: (state, getters) => groupId => {
    return getters.getTasksByGroup(groupId).filter(task => task.status === 'doing');
  },
  
  // 获取指定分组的已完成任务
  getDoneTasksByGroup: (state, getters) => groupId => {
    return getters.getTasksByGroup(groupId).filter(task => task.status === 'done');
  }
};

const mutations = {
  SET_TASKS(state, tasks) {
    console.log('【Vuex】设置任务列表:', tasks.length);
    state.tasks = tasks;
    // 保存到本地存储
    saveTasksToStorage(tasks);
  },
  
  ADD_TASK(state, task) {
    console.log('【Vuex】添加任务:', task.title);
    state.tasks.push(task);
    // 保存到本地存储
    saveTasksToStorage(state.tasks);
  },
  
  UPDATE_TASK(state, updatedTask) {
    console.log('【Vuex】更新任务:', updatedTask.title);
    const index = state.tasks.findIndex(task => task.id === updatedTask.id);
    if (index !== -1) {
      state.tasks.splice(index, 1, updatedTask);
      console.log('【Vuex】任务更新成功');
      // 保存到本地存储
      saveTasksToStorage(state.tasks);
    } else {
      console.log('【Vuex】任务更新失败: 未找到对应ID的任务');
    }
  },
  
  DELETE_TASK(state, taskId) {
    console.log('【Vuex】删除任务:', taskId);
    state.tasks = state.tasks.filter(task => task.id !== taskId);
    if (state.currentTaskId === taskId) {
      state.currentTaskId = '';
    }
    // 保存到本地存储
    saveTasksToStorage(state.tasks);
  },
  
  SET_CURRENT_TASK(state, taskId) {
    console.log('【Vuex】设置当前任务:', taskId);
    state.currentTaskId = taskId;
  }
};

const actions = {
  // 初始化任务数据
  async initTasks({ commit }) {
    try {
      // 先尝试从本地存储加载数据
      const storedTasks = loadTasksFromStorage();
      
      if (storedTasks && storedTasks.length > 0) {
        // 如果本地存储有数据，使用本地数据
        commit('SET_TASKS', storedTasks);
      } else {
        // 如果本地存储没有数据，使用默认数据
        const mockTasks = [
          new Task({
            id: 'task1',
            title: '每日喝水2L',
            description: '保持身体水分平衡',
            priority: 'high',
            tags: ['健康'],
            groupId: 'group5',
            deadline: Date.now() + 86400000, // 明天
            status: 'todo',
            order: 1
          }),
          new Task({
            id: 'task2',
            title: '冥想练习',
            description: '每天15分钟冥想',
            priority: 'low',
            tags: ['健康', '心理'],
            groupId: 'group5',
            deadline: Date.now() + 172800000, // 后天
            status: 'todo',
            order: 2
          }),
          new Task({
            id: 'task3',
            title: '晨跑30分钟',
            description: '清晨慢跑30分钟',
            priority: 'medium',
            tags: ['健康', '运动'],
            groupId: 'group5',
            deadline: Date.now(),
            status: 'done',
            order: 3
          }),
          new Task({
            id: 'task4',
            title: '健康饮食',
            description: '摄入均衡营养',
            priority: 'medium',
            tags: ['健康', '饮食'],
            groupId: 'group5',
            deadline: Date.now() - 86400000, // 昨天
            status: 'done',
            order: 4
          })
        ];
        
        commit('SET_TASKS', mockTasks);
      }
    } catch (error) {
      console.error('初始化任务数据失败', error);
    }
  },
  
  // 创建新任务
  createTask({ commit }, taskData) {
    const newTask = new Task({
      ...taskData,
      id: 'task_' + Date.now(), // 简单的ID生成
      createTime: Date.now(),
      updateTime: Date.now()
    });
    
    commit('ADD_TASK', newTask);
    return newTask;
  },
  
  // 更新任务
  updateTask({ commit }, taskData) {
    const updatedTask = new Task({
      ...taskData,
      updateTime: Date.now()
    });
    
    commit('UPDATE_TASK', updatedTask);
    return updatedTask;
  },
  
  // 删除任务
  deleteTask({ commit }, taskId) {
    commit('DELETE_TASK', taskId);
  },
  
  // 删除指定分组的所有任务
  deleteTasksByGroupId({ commit, state }, groupId) {
    if (!groupId) return;
    
    console.log('【Vuex】删除分组任务:', groupId);
    const tasksToDelete = state.tasks.filter(task => task.groupId === groupId);
    if (tasksToDelete.length > 0) {
      tasksToDelete.forEach(task => {
        commit('DELETE_TASK', task.id);
      });
      console.log(`【Vuex】已删除${tasksToDelete.length}个任务`);
    }
  },
  
  // 设置当前任务
  setCurrentTask({ commit }, taskId) {
    commit('SET_CURRENT_TASK', taskId);
  },
  
  // 切换任务状态
  toggleTaskStatus({ commit, state }, taskId) {
    const task = state.tasks.find(task => task.id === taskId);
    if (!task) return;
    
    let newStatus = 'todo';
    if (task.status === 'todo') newStatus = 'doing';
    else if (task.status === 'doing') newStatus = 'done';
    else if (task.status === 'done') newStatus = 'todo';
    
    const updatedTask = new Task({
      ...task,
      status: newStatus,
      updateTime: Date.now()
    });
    
    commit('UPDATE_TASK', updatedTask);
    return updatedTask;
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}; 